package com.example.commons.util;

import com.example.commons.annotation.DebounceLock;
import com.example.commons.annotation.DebounceLockParam;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 生成锁的key值
 */
public class RequestKeyGenerator {

    public static String getLockKey(ProceedingJoinPoint joinPoint) {
        //获取连接点的方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //Method对象
        Method method = signature.getMethod();
        //获取Method对象上的注解
        DebounceLock debounceLock= method.getAnnotation(DebounceLock.class);
        //获取方法参数
        final Object[] args = joinPoint.getArgs();
        final Parameter[] parameters = method.getParameters();
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<parameters.length; i++) {
            DebounceLockParam annotation = parameters[i].getAnnotation(DebounceLockParam.class);
            if(annotation == null) {   //不是 则不做处理
                continue;
            }
            //如果是 则拼接
            sb.append(debounceLock.split()).append(args[i]);

        }
        if(StringUtils.isEmpty(sb.toString())) {
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for(int i=0; i<parameterAnnotations.length; i++) {
                Object object = args[i];
                Field[] declaredFields = object.getClass().getDeclaredFields();
                 for(Field field : declaredFields) {
                     DebounceLockParam annotation = field.getAnnotation(DebounceLockParam.class);
                     if(annotation == null) {
                         continue;
                     }
                     field.setAccessible(true);
                     sb.append(debounceLock.split()).append(ReflectionUtils.getField(field, object));
                 }
            }


        }
        return debounceLock.prefix()+sb;
    }



}
